package com.xiangxiao.rpan.data.mqtt;

import com.xiangxiao.rpan.data.factory.ApplicationContextFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
/**
 * @auther xiangxiao
 * @email 573768011@qq.com
 * @data 2024/6/14 11:24
 */
@Component
public class MqttDataCallback implements MqttCallback {
  private static Logger logger = LogManager.getLogger(MyMqttServer.class);

  @Resource
  private MyMqttServer mqttConfig;

  /**
   * 与MQTT服务器连接断开后的回调
   * @param throwable
   */
  @Override
  public void connectionLost(Throwable throwable) {
    // 连接丢失后，一般在这里面进行重连
    logger.info("[MQTT] 连接断开，10S之后尝试重连...");
    while (true){
      try {
        Thread.sleep(10000);
        mqttConfig.reConnect();
        break;
      }catch (Exception e){
        e.printStackTrace();
        continue;
      }
    }
  }

  /**
   * 接收所订阅Topic推送的消息
   * @param topic
   * @param mqttMessage
   * @throws Exception
   */
  @Override
  public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
    String result = mqttMessage.toString();
    logger.info("#####接收到的数据："+result);
  }

  @Override
  public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

  }
}
